package com.xliu.cs.openprojects.videoplay.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class ByteRangeController {
    @Autowired
    private NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    /**
     * 支持的视频格式，直接使用支持 byte-range 请求
     */
    @GetMapping("/video/byte-range")
    public void videoPreview(@RequestParam String path, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Path filePath = Paths.get(path);
        System.out.println("Path: is " + filePath.toFile().getAbsolutePath());

        if (Files.exists(filePath)) {
            String mimeType = Files.probeContentType(filePath);
            if (StringUtils.hasLength(mimeType)) {
                response.setContentType(mimeType);
            }
            request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getOutputStream().write("Video file not found".getBytes(StandardCharsets.UTF_8));
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }
}